package com.action.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.log4j.Logger;

import com.base.BaseAction;
import com.base.UserBean;
import com.bean.RulerInfo;
import com.bean.RulerMethod;
import com.bean.RulerRole;
import com.bean.SysUser;
import com.dao.RulerDao;
import com.service.RulerService;
import com.service.SysUserService;
import com.util.Browser;
import com.util.G;
import com.util.GUtil;

public class LoginAction extends BaseAction {

	private static final Logger log = Logger.getLogger(RulerDao.class);

	private static final long serialVersionUID = 1L;
	SysUserService sysUserService;
	RulerService rulerService;
	RulerInfo ruInfo;

	String userName;
	String password;
	String captcha;

	Integer flag;

	String helpurl = "#";
	private Browser broswer;

	public void preLogin(){

		loginAction = "LoginAction";
		this.addCookie("loginAction", loginAction);

		//get RedirectUrl from cookie
		if(RedirectUrl==null){
			Cookie cookie = GUtil.getCookieByName(request, "RedirectUrl");
			if(cookie!=null)
				RedirectUrl = cookie.getValue();
		}

		if(RedirectUrl!=null && !RedirectUrl.trim().isEmpty()){
			session.put("RedirectUrl", RedirectUrl);
			this.addCookie("RedirectUrl", RedirectUrl);
		}
	}

	public String checkBrowser(){
		if(IgnoreBrowser==null)
			IgnoreBrowser = (Boolean) session.get("IgnoreBrowser");
		if(IgnoreBrowser!=null && IgnoreBrowser==true){
			session.put("IgnoreBrowser", IgnoreBrowser);
		}else{
			broswer = new Browser(request);
			if(broswer.getName().startsWith("MSIE")){
				this.setMsg("请使用非IE浏览器,如使用的是360浏览器,请选择\"极速模式\",详见 <a href=\""+helpurl+"\">帮助</a>" +
						//	"&nbsp |&nbsp <font size=small><a href="+this.action+"?IgnoreBrowser=true >忽略并继续</a></font>" " +
						"  ");//"
				return GUtil.ERROR;
			}
		}
		return GUtil.SUCCESS;
	}


	@Override
	public String handle() throws Exception {

		this.setLoginAction("LoginAction");
		this.setTitle( sc.getInitParameter("title") );

		String retMapping = GUtil.NONE;
		String ret = this.checkBrowser();
		if( !ret.equals(GUtil.SUCCESS)){
			return ret;
		}

		this.preLogin();
		session.put("RedirectUrl", "");
		this.addCookie("loginAction", "");
		this.addCookie("RedirectUrl", "");

		if(flag!=null && flag==1 && user!=null){
			//登录成功，返回指定页面
			if( RedirectUrl !=null && !RedirectUrl.isEmpty() ){
				response.sendRedirect(RedirectUrl);
				return GUtil.NONE;
			}
			return GUtil.SUCCESS;
		}

		if(method==null)
			return GUtil.LOGIN;
		if (method.equals("login")) {
			retMapping = login();
		}
		if (method.equals("logout")) {
			retMapping = logout();
		}

		return retMapping;
	}

	public String logout() {

		this.addCookie("loginAction", "LoginAction");

		if(user!=null)
		{
			log.info("ParkLogin logout @ user:  "+user.getUserCode()+"["+user.getUserName()+"]  logout");
			System.out.println(" user:  "+user.getUserCode()+"["+user.getUserName()+"]  logout");
		}
		session.clear();
		return LOGIN;
	}

	/**
	 *  登录系统，获取所有权限和操作菜单，并存入session
	 * @return 
	 * @throws Exception
	 */
	public String login() throws Exception {

		List<Integer>  idlist =  new ArrayList<Integer>() ;
		List<RulerRole> rulerRoleList = null;
		List<RulerInfo> rulerInfolist = null;

		String ip = GUtil.parseIp(request, response);

		this.preLogin();

		//用户的session还未失效，暂时不需要再次通过数据库登录
		if(session.get("user")!=null && session.get("sysuser")!=null){
			user = (UserBean) session.get("user");
			if(RedirectUrl==null)
				RedirectUrl = (String) session.get("RedirectUrl");
			if( RedirectUrl !=null && !RedirectUrl.isEmpty() ){
				response.sendRedirect(RedirectUrl);
				return GUtil.NONE;
			}
			return GUtil.SUCCESS;
		}

		//通过查询数据库进行登录
		if (user == null) {
			log.info("来自 IP="+ip + " 的系统管理用户请求登录");
			return LOGIN; // 浏览器输入 http://127.0.0.1/oa/LoginAction?method=login 返回空操作和空消息
		}

		Long t1 = System.currentTimeMillis();
		if(user.getUserCode()==null || user.getUserCode().trim().isEmpty()){
			msg = "帐号不能为空";
			return GUtil.LOGIN;
		}
		if(user.getUserPasswd()==null || user.getUserPasswd().trim().isEmpty()){
			msg = "密码不能为空";
			return GUtil.LOGIN;
		}

		SysUser userCheck = sysUserService.login(user.getUserCode(), user.getUserPasswd(), ip);
		if (userCheck == null) {
			msg = "用户名或密码错误";
			log.info(msg+" ip="+ip);
			return GUtil.LOGIN;
		}else {
			if(userCheck.getStatus()!=1){
				this.setMsg("抱歉,用户状态["+userCheck.getStatusName()+"],如有疑问请联系管理员!");
				return GUtil.LOGIN;
			}

			if(user==null)
				user = new UserBean();
			user.setUser(userCheck);
			session.put("sysuser", userCheck);
			session.put("loginAction", "LoginAction");
			user.setIp(ip);
			Long roleId = user.getRole();//获取角色id

			log.info("----------------  LoginAction login() -------------------------");

			Long t2 = System.currentTimeMillis();
			rulerRoleList = rulerService.rulerRole(roleId);//根据roleid获取本用户的所有权限 rulerid, rulerword
			Long t3 = System.currentTimeMillis();

			if(rulerRoleList==null ){
				msg  = "您没有任何权限，如有疑问，请联系管理员";
				log.info(msg+" ip="+ip);
				return GUtil.LOGIN;
			}
			//获取所有权限
			for(RulerRole rr : rulerRoleList){
				idlist.add( rr.getRulerId() );
				//	log.info( rr.getRulerId()+"=" + rr.getRulerWord());
			}

			Long t4 = System.currentTimeMillis();
			rulerInfolist = (List<RulerInfo>) rulerService.queryRulerList(idlist);//根据权限ID(ruler id)获取对应的菜单
			List<RulerMethod> methodsList = rulerService.queryMethds(null, false);
			Long t5 = System.currentTimeMillis();

			//将 菜单rulerInfolist 和 改菜单的权限rulerRoleList进行map合并
			//Map<action, RulerInfo >
			Map<String, RulerInfo > rulermap = calcRoleRight(rulerRoleList, rulerInfolist, methodsList);

			session.put("user", user);
			session.put("rulermap", rulermap);
			//	session.put("rulerRoleList", rulerRoleList);//本用户的所有权限 rulerid, rulerword
			session.put("rulerInfolist", rulerInfolist);//本用户的菜单

			//登录成功，返回指定页面
			if(RedirectUrl==null)
				RedirectUrl = (String) session.get("RedirectUrl");
			if( RedirectUrl !=null && !RedirectUrl.isEmpty() ){
				response.sendRedirect(RedirectUrl);
				return GUtil.NONE;
			}
			Long t6 = System.currentTimeMillis();
			log.info("LoginAction.login()[登录成功] [ip="+ip+" usercode="+user.getUserCode()+" login total takes "+(t6-t1)+"ms] " +
					"[获取本用户的所有权限 takes "+(t3-t2)+"ms ] [根据权限ID(ruler id)获取对应的菜单 "+(t5-t4)+"ms] ");

			return GUtil.SUCCESS;
		}
	}

	/**
	 * 权限计算
	 * <p>Title: calcRoleRight</p>
	 * <p>Description: </p>
	 * @return
	 */
	public static Map<String, RulerInfo > calcRoleRight(List<RulerRole> rulerRoleList, List<RulerInfo> rulerInfolist, List<RulerMethod> methodsList){
		//将 菜单rulerInfolist 和 改菜单的权限rulerRoleList进行map合并
		//Map<action, RulerInfo >
		Map<String, RulerInfo > rulermap = new HashMap<String, RulerInfo>();
		//Map<method, RulerMethod>
		Map<String, RulerMethod>  methodmap = null;
		RulerMethod rulerMethod = null;
		String action = null;
		String rulerword = null;
		String temp [] =null;

		if(G.debug)
			log.info("------------------- 权限列表 ---------------------");
		for(RulerInfo ri : rulerInfolist){
			action = ri.getUrl();//get action
			if(action.trim().isEmpty() || action.endsWith("#"))
				continue;
			if(G.debug)
				log.info("    id="+ri.getRulerid()+" action="+ri.getUrl()+" name="+ri.getRulerName());
			for(RulerRole rr : rulerRoleList){
				if( (rr.getRulerId() - ri.getRulerid())==0 ){
					methodmap =  new  HashMap<String, RulerMethod>();
					//get rulerRole
					rulerword = rr.getRulerWord();
					if(rulerword!=null && !rulerword.trim().isEmpty())
					{
						try{
							temp = rulerword.split(";");
							for(String method : temp){
								if(method!=null && !method.isEmpty()){
									for(RulerMethod rm : methodsList){
										//get & set rulerMethod for ri 
										if( (rm.getRulerId()-ri.getRulerid())==0  ){
											if(rm.getMethod().trim().equals(method.trim())){
												methodmap.put(method.trim(), rm);
												if(G.debug)
													log.info("        --method="+rm.getMethod()+" name="+rm.getName());
												break;
											}
										}
									}//end for
								}//end if
							}//end for
						}catch (Exception e) {
							log.error(e.getMessage());
						}
					}//end if
					ri.setMethodmap(methodmap);
				}
			}
			rulermap.put(action, ri);
		}
		if(G.debug)
			log.info("----------------------------------------");
		return rulermap;
	}

	public RulerService getRulerService() {
		return rulerService;
	}

	public void setRulerService(RulerService rulerService) {
		this.rulerService = rulerService;
	}

	public RulerInfo getRuInfo() {
		return ruInfo;
	}

	public void setRuInfo(RulerInfo ruInfo) {
		this.ruInfo = ruInfo;
	}


	@Override
	public String add() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String query() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String update() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String view() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean validate(Object obj) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}


	public Integer getFlag() {
		return flag;
	}

	public void setFlag(Integer flag) {
		this.flag = flag;
	}

	/**
	 * @return the sysUserService
	 */
	public SysUserService getSysUserService() {
		return sysUserService;
	}

	/**
	 * @param sysUserService the sysUserService to set
	 */
	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}



}
